package com.stedu.mall.adminservice.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.stedu.mall.common.bean.Admin;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.AdminService;
import com.stedu.mall.common.utils.JwtUtils;
import com.stedu.mall.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisUtil redisUtil;
    @GetMapping("/captcha")
    public RespBean captcha() {//验证码
        //生成验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 38, 4, 10);
        //获取验证码的文本
        String code = captcha.getCode();
        //生成唯一的ID
        String key = IdUtil.getSnowflakeNextIdStr();
        //获取验证码文本保存到redis中,超时时间100s
        redisUtil.set(key, code, 100);
        //图片进行Base64-->字符串
        String captchaImageBase64Data = captcha.getImageBase64Data();
        //将key和base64编码保存在map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", key);
        map.put("captchaImageBase64Data", captchaImageBase64Data);
        //将key和base64编码返回
        return RespBean.ok("", map);
    }

    @PostMapping("/login")
    //key是上边获取验证码得到的
    public RespBean login(@Validated String username, String password, String key, String captchaInput) throws SteduException {
        /*
         判断验证码  -- 和Redis中保存的验证码文本相比
        */
        String captchaRedis = (String) redisUtil.get(key);
        if (captchaRedis == null || !captchaRedis.equalsIgnoreCase(captchaInput)) {
            return RespBean.error("验证码错误，请重试");
        }
        //登录
        Admin admin = adminService.login(username, password);
        //生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        map.put("role", "admin");
        String jwt = JwtUtils.generateJwt(map);
        //token返回用户
        return RespBean.ok("登陆成功", jwt);
    }
    //后端接收并解析前端传来的jwt，获取已登录用户的信息
    @GetMapping("/info")
    public RespBean getInfo(@RequestHeader("token") String token) {
        //不需要获取jwt,直接解析
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id
        Integer id = (Integer) map.get("id");

        //通过id查询用户信息
        Admin admin = adminService.selectById(id);
        //返回
        return RespBean.ok("", admin);
    }
    //修改密码
    @PutMapping("/changePwd")
    public RespBean changePwd(String oldPwd, String newPwd, String newPwd1 ,@RequestHeader("token") String token) throws SteduException {
        if (!newPwd.equals(newPwd1)){
            throw new SteduException("两次输入的密码不一致，请重新输入");
        }
        //不需要获取jwt,直接解析
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id
        Integer id = (Integer) map.get("id");
        //通过id查询用户信息
        adminService.changePwd(oldPwd,newPwd,id);
        //返回
        return RespBean.ok("修改成功");
    }
    //增加
    @PostMapping
    public RespBean insert(@RequestBody Admin admin) throws SteduException {
        adminService.insert(admin);
        return RespBean.ok("添加成功");
    }
    // 删除(软删)
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id) throws SteduException {
        adminService.delete(id);
        return RespBean.ok("修改状态成功");
    }
    // 修改
    @PutMapping
    public RespBean update(@RequestBody Admin admin) throws SteduException {
        adminService.update(admin);
        return RespBean.ok("修改成功");
    }
    //重置密码
    @PutMapping("/{id}")
    public RespBean back(@PathVariable("id") Integer id) throws SteduException {
        adminService.back(id);
        return RespBean.ok("修改成功");
    }
    //根据id查询
    @GetMapping("/{id}")
    //@IgnoreToken
    public RespBean selectById(@PathVariable("id") Integer id) {
        return RespBean.ok("", adminService.selectById(id));
    }
    //分页查询
    @GetMapping("/search")
    public RespBean selectByPage(Admin condition, Integer pageNum, Integer pageSize) {
        //前端可能没传过来pageNum,pageSize
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 5 : pageSize;
        Object data = adminService.selectByCondition(condition, pageNum, pageSize);
        return RespBean.ok("", data);
    }

    @GetMapping("/top5Dept")
    public RespBean top5Dept() {
        List<Map<String, Object>> maps = adminService.selectTop5Dept();
        return RespBean.ok("", maps);
    }

    @GetMapping("/userOrder")
    public RespBean userOrder() {
        List<Map<String, Object>> maps = adminService.selectUserOrder();
        return RespBean.ok("", maps);
    }
}
